<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert
        show-icon
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 级联选择 -->
      <el-row class="cat_opt">
        <el-col>
          <span
            >选择商品分类:
            <el-cascader
              v-model="selectKeyValue"
              :options="cateList"
              :props="selectList"
              @change="handleChange"
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            :disabled="iSTabButton"
            size="mini"
            >添加参数</el-button
          >
          
          <!-- 动态参数 数据表格 -->
          <el-table :data="manyTableValue">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- Tag遍历的数据 -->
                <el-tag
                  closable
                  type="success"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close = "removeClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            :disabled="iSTabButton"
            size="mini"
            >添加属性</el-button
          >
          <!-- 静态属性 数据表格 -->
          <el-table :data="onlyTableValue">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  type="success"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close = "removeClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                 <!-- 添加 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  @click="delParams(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加功能对话框 -->
    <el-dialog
      :title="'添加' + TitleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="Delform"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="TitleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProms()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + TitleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="Delform"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="TitleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editProms()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      //级联选择器的配置对象
      selectList: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选择的数据
      selectKeyValue: [],
      // 标签页双休数据
      activeName: 'many',
      //动态参数的数据
      manyTableValue: [],
      // 静态属性的数据
      onlyTableValue: [],
      //显示的与隐藏对话框
      addDialogVisible: false,
      editDialogVisible: false,
      //对话框数据
      addForm: [],
      addFormRules: {
        attr_name: [
          { required: true, message: '数据不能为空', trigger: 'blur' }
        ]
      },
      //修改对话框数据
      editForm: [],
      editFormRules: {
        attr_name: [
          { required: true, message: '数据不能为空', trigger: 'blur' }
        ]
      },
      
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取分类数据失败')
      this.cateList = res.data
      console.log('cateList')
    },
    // 级联选中器选择数据触发的事件
    handleChange() {
      this.getParamsList()
    },
    //标签页事件
    handleTabClick() {
      this.getParamsList()
      console.log(this.activeName)
    },
    // 获取参数列表数据
    async getParamsList() {
      //判断选择的是否是三级分类
      if (this.selectKeyValue.length !== 3) {
        this.selectKeyValue = []
        this.manyTableValue = []
        this.onlyTableValue = []
        return
      }
      // 根据所选分类的Id,和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.creaId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //输入框的显示与隐藏
        item.inputVisible = false
        //文本框输入的值
        item.inputValue=''
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      if (this.activeName == 'many') {
        this.manyTableValue = res.data
      } else {
        this.onlyTableValue = res.data
      }
      console.log(res.data)
    },
    //对话框关闭清空表单
    Delform() {
      this.$refs.addFormRef.resetFields()
    },
    //添加参数或属性
    addProms() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.creaId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParamsList()
      })
    },
    // 显示对话框
    async editDialog(attr_id) {
      console.log(attr_id)
      const { data: res } = await this.$http.get(
        `categories/${this.creaId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //编辑对话框关闭清空事件
    Delform() {
      this.$refs.editFormRef.resetFields()
    },
    //修改参数或属性
    editProms() {
      this.$refs.editFormRef.validate(async valid => {
        const { data: res } = await this.$http.put(
          `categories/${this.creaId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getParamsList()
        this.editDialogVisible = false
      })
    },
    // 删除数据
    async delParams(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.creaId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParamsList()
    },
   async handleInputConfirm(row){
      //判断输入的值是否有效
      if(row.inputValue.trim().length===0){
         row.inputValue=''
         this.inputVisible = false
         return
      }
      // 如果没有return 则执行上传数据操作
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue=''
      row.inputVisible=false
      this.defHand(row)
      // this.getParamsList()
      
    },
    async defHand(row){
      const{data:res} = await this.$http.put(`categories/${this.creaId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200)
        return this.$message.error('操作失败')
      this.$message.success('操作成功')
    },
    showInput(row){
      row.inputVisible = true
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //删除tag标签数据
    removeClose(i,row){
      row.attr_vals.splice(i,1)
      this.defHand(row)
    }
  },
  computed: {
    iSTabButton() {
      if (this.selectKeyValue.length !== 3) return true
      return false
    },
    //获取当前选中的三级分类Id
    creaId() {
      if (this.selectKeyValue.length !== 3) return null
      return this.selectKeyValue[2]
    },
    TitleText() {
      if (this.activeName == 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>
